package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.ruoyi.common.config.BigDataConfig;
import com.ruoyi.common.core.domain.JSONObjectPro;
import com.ruoyi.common.core.page.Page;
import com.ruoyi.common.exception.BigDataException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SnowFlakeIDGenerator;
import com.ruoyi.common.utils.http.BigDataResponse;
import com.ruoyi.common.utils.http.HttpRequest;
import com.ruoyi.system.domain.request.historyvideo.HistoryVideoDeviceCloseParam;
import com.ruoyi.system.domain.request.historyvideo.HistoryVideoDeviceListParam;
import com.ruoyi.system.domain.request.historyvideo.HistoryVideoServiceListParam;
import com.ruoyi.system.domain.request.realtimevideo.ServerVideo;
import com.ruoyi.system.domain.vo.common.ComDvoName;
import com.ruoyi.system.domain.vo.realtimevideo.DeviceVideo;
import com.ruoyi.system.service.IEquipmentManagementService;
import com.ruoyi.system.service.IHistoryVideoService;
import com.ruoyi.system.service.OrderSendService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述 历史视频Service实现类
 * 作者 ZhangPing
 * 创建时间 2023/10/30 14:26
 */
@Service
public class HistoryVideoServiceImpl implements IHistoryVideoService {

    @Autowired
    private BigDataConfig bigDataConfig;
    @Autowired
    private IEquipmentManagementService equipmentManagementService;
    @Autowired
    private OrderSendService orderSendService;

    /**
     * 历史视频列表
     */
    @Override
    public Page<JSONObject> serverList(HistoryVideoServiceListParam param){
        BigDataResponse<List<JSONObject>> response = HttpRequest.postJsonBigData(bigDataConfig.getApiUrl() + "/video/queryHisList",
                param.toJson(), new TypeReference<List<JSONObject>>(){}.getType());
        if (!response.isSuccess()) throw new BigDataException();
        List<JSONObject> data = response.getData();
        int total = response.getTotalCount();
        ComDvoName comDvoNames = equipmentManagementService.selectDeviceAndCompanyName(param.getDvo());
        String numberPlate = comDvoNames == null ? "" : comDvoNames.getNumberPlate();
        String companyName = comDvoNames == null ? "" : comDvoNames.getCompanyName();
        List<JSONObject> resultList = data.stream().map(i -> {
            JSONObjectPro item = new JSONObjectPro()
                .put("vehNo", numberPlate)
                .put("dvoNo", param.getDvo())
                .put("companyName", companyName)
                .put("channel", i.get("channel"))
                .put("startTime", i.get("startTime"))
                .put("endTime", i.get("endTime"))
                .put("streamType", i.get("streamType"))
                .put("httpUrl", i.get("httpUrl"));
            return item;
        }).collect(Collectors.toList());
        return new Page<>(total, resultList);
    }

    /**
     * 设备历史视频列表
     */
    @Override
    public Page<JSONObject> deviceList(HistoryVideoDeviceListParam param){
        if (DateUtils.parseDate(param.getEndTime()).getTime() - DateUtils.parseDate(param.getStartTime()).getTime() > 24 * 60 * 60 * 1000){
            throw new ServiceException("时间范围不能超过一天");
        }
        List<DeviceVideo> videoList = orderSendService.queryMediaList(param);
        ComDvoName comDvoNames = equipmentManagementService.selectDeviceAndCompanyName(param.getDvo());
        String numberPlate = comDvoNames == null ? "" : comDvoNames.getNumberPlate();
        String companyName = comDvoNames == null ? "" : comDvoNames.getCompanyName();
        List<JSONObject> list = videoList.stream().map(i -> {
            JSONObjectPro item = new JSONObjectPro()
                    .put("vehNo", numberPlate)
                    .put("dvoNo", param.getDvo())
                    .put("companyName", companyName)
                    .put("channel", i.getChanelId())
                    .put("startTime", DateUtils.parseDateTime(new Date(i.getStartTime())))
                    .put("endTime", DateUtils.parseDateTime(new Date(i.getEndTime())))
                    .put("streamType", 0);
            return item;
        }).sorted((item1, item2) -> item2.get("startTime").toString().compareTo(item1.get("startTime").toString())).collect(Collectors.toList());
        return new Page<>(list.size(), list);
    }

    /**
     * 开启设备历史视频
     * @param param
     */
    @Override
    public void openDeviceVideo(HistoryVideoDeviceListParam param){
        orderSendService.openDeviceVideo(param);
    }

    /**
     * 关闭设备历史视频
     * @param param
     */
    @Override
    public void closeDeviceVideo(HistoryVideoDeviceCloseParam param){
        orderSendService.closeDeviceVideo(param);
    }

    /**
     * 获取视频信息
     * @param param
     */
    @Override
    public Object getVideoInfo(HistoryVideoDeviceCloseParam param){
        JSONObjectPro bitDataParam = new JSONObjectPro()
                .put("dvo", param.getDvo())
                .put("channel", param.getChannel());
        BigDataResponse<List<JSONObject>> response = HttpRequest.postJsonBigData(bigDataConfig.getApiUrl() + "/video/queryHis",
                bitDataParam, new TypeReference<List<JSONObject>>() {}.getType());
        if (!response.isSuccess()) throw new BigDataException();
        return ObjectUtils.isNotEmpty(response.getData()) ? response.getData().get(0) : null;
    }

    /**
     * 服务器指定历史视频
     * @param param
     */
    @Override
    public Object queryTargetHisMedia(HistoryVideoDeviceListParam param){
        JSONObjectPro bigDataParam = new JSONObjectPro()
                .put("dvo", param.getDvo())
                .put("channel", param.getChannel())
                .put("streamType", param.getMediaType())
                .put("startTime", param.getStartTime())
                .put("endTime", param.getEndTime());
        BigDataResponse<List<JSONObject>> response = HttpRequest.postJsonBigData(bigDataConfig.getApiUrl() + "/videoHisMedia/queryTargetHisMedia",
                bigDataParam, new TypeReference<List<JSONObject>>() {}.getType());
        if (!response.isSuccess()) throw new BigDataException();
        if (ObjectUtils.isNotEmpty(response.getData())) {
            JSONObject jsonObject = response.getData().get(0);
            return jsonObject;
        }
        return null;
    }

    /**
     * 删除服务器指定历史视频
     * @param rowKeyList
     */
    @Override
    public boolean deleteHisMediaList(List<String> rowKeyList){
        JSONObjectPro bitDataParam = new JSONObjectPro()
                .put("rowKeyList", rowKeyList);
        BigDataResponse<Integer> response = HttpRequest.postJsonBigData(bigDataConfig.getApiUrl() + "/videoHisMedia/deleteHisMediaList",
                bitDataParam, new TypeReference<Integer>() {}.getType());
        if (!response.isSuccess()) throw new BigDataException();
        return response.isSuccess();
    }
}
